﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using Newtonsoft.Json;
using System.Web.Services;
using RN.ERP.Web.ModelService;
using RN.ERP.Web.PersonService;
using RN.ERP.Web.OrderService;
using Fly.Common.Linq;
using System.Configuration;
using System.Text;

namespace RN.ERP.Web.Exam
{
    public partial class BmList : BasePage
    {
        #region Params

        /// <summary>
        /// 专家系统支付(不随考试期次，科目变化)
        /// </summary>
        private string GROUP_CODE = "EXP";

        /// <summary>
        /// 专家系统支付(不随考试期次，科目变化)
        /// </summary>
        private string PRODUCT_CODE = "EXP01";

        private string CurPageCode = "BM";

        private string CurPage = "BmList.aspx";

        /// <summary>
        /// 支付链接
        /// </summary>
        public string PayWebSite
        {
            get
            {
                return ConfigurationManager.AppSettings["PayWebSite"];
            }
        }

        public string AppID
        {
            get
            {
                return HttpContext.Current.Application[ApplicationConstant.APPLICATION_ID].ToString();
            }
        }

        public string RoleId
        {
            get
            {
                return UserInfo.RoleId;
            }
        }

        private PersonServiceClient psnClient = new PersonServiceClient();

        private OrderServiceClient oClient = new OrderServiceClient();

        public string RoleType
        {
            get
            {
                return UserInfo.RoleType;
            }
        }

        #endregion

        #region Init & DataBind

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ////绑定期次下拉
                BindQCDDL();
                
                ControlInit(RoleType);

                ////地区号，主管端根据地区筛选数据
                hidArea.Value = Request.QueryString["areacode"];
                string title = Request.QueryString["title"];
                
                if (!string.IsNullOrEmpty(title))
                {
                    lbAreaTitle.Text = title;
                }
            }
        }

        /// <summary>
        /// 根据角色 设置控件的显隐
        /// </summary>
        /// <param name="roleType">角色类型</param>
        private void ControlInit(string roleType)
        {
            if (roleType == "Manager")
            {
                ////主管 隐藏【缴费】按钮
                ////隐藏【期次】【考试说明】【订单号】列、【注意事项】

                lbBMPay.Visible = notice.Visible = false;
                RadGrid1.Columns[1].Visible = RadGrid1.Columns[5].Visible = 
                    RadGrid1.Columns[9].Visible = RadGrid1.Columns[6].Visible = false;
                ddlQC.SelectedValue = Request.QueryString["qc"];
                if (Request["type"] == "1")////在未报名列表页 显示手机号
                {
                    RadGrid1.Columns[10].Visible = true;
                }
            }
            else
            {
                ////专家  隐藏【名称】【报名缴费开始时间】【报名缴费截止时间】列
                ////      隐藏【返回】按钮，身份证号查询框，姓名查询框
                RadGrid1.Columns[3].Visible = RadGrid1.Columns[7].Visible = RadGrid1.Columns[8].Visible = false;
                spReturn.Visible = IDCardSearch.Visible = expertNameSearch.Visible = false;
            }
        }

        /// <summary>
        /// 数据加载
        /// </summary>
        protected void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            BindData();
        }

        /// <summary>
        /// 绑定数据
        /// </summary>
        private void BindData()
        {
            if (RoleType == "Manager")////主管登录时绑定数据
            {
                BindDataManager();
            }
            else////专家登录时绑定数据
            {
                BindDataExpert();
            }
        }

        /// <summary>
        /// 专家登录时绑定数据
        /// </summary>
        private void BindDataExpert()
        {
            RadGrid1.AllowCustomPaging = false;
            int qc = 0;
            int.TryParse(ddlQC.SelectedValue, out qc);
            using (PersonServiceClient client = new PersonServiceClient())
            {
                int count = 0;
                var exam = new List<ExamInfo>();
                List<Exam_QC> qcList = GetQC(RoleId, AppID, true);

                ////已报名期次列表
                var bm = client.GetExamBMList(CurPageCode, UserInfo.RoleId, CurPage, AppID
                    , qc, hidArea.Value, GetQueryEmpCondition(), 0, 0, 10000, out count);

                if (bm != null)
                {
                    exam = JsonConvert.DeserializeObject<List<ExamInfo>>(bm);
                }
                
                ////没报名的期次列表
                var notSignList = qcList.Where(c => !exam.Exists(e => e.QCID == c.ID))
                    .Select<Exam_QC, ExamInfo>(c => new ExamInfo
                    {
                        QCID = c.ID,
                        Title = c.Title,
                        EndDate = c.EndDate,
                        StartDate = c.StartDate,
                        ExamDate = c.ExamDate,
                        CorpUserGuid = Guid.Parse(UserInfo.CorpUserGuid),
                        OrderCode=""
                    });

                exam.AddRange(notSignList);
                exam = exam.Where(e => qcList.Exists(q => q.ID == e.QCID)).ToList();

                RadGrid1.VirtualItemCount = exam.Count;
                RadGrid1.DataSource = exam;
            }
        }

        /// <summary>
        /// 主管登录时绑定数据
        /// </summary>
        private void BindDataManager()
        {
            RadGrid1.AllowCustomPaging = true;
            int pageCount = RadGrid1.CurrentPageIndex;
            int pageSize = RadGrid1.PageSize;
            int qc = 0;
            int.TryParse(ddlQC.SelectedValue, out qc);
            int requestType = 0;
            string requestTypeStr = Request.QueryString["type"];
            int.TryParse(requestTypeStr, out requestType);

            using (PersonServiceClient client = new PersonServiceClient())
            {
                int count = 0;
                var bm = client.GetExamBMList(CurPageCode, UserInfo.RoleId, CurPage,
                    AppID, qc, hidArea.Value, GetQueryEmpCondition(), requestType, 
                    pageCount + 1, pageSize, out count);
                var exam = new List<ExamInfo>();
                if (bm != null)
                {
                    exam = JsonConvert.DeserializeObject<List<ExamInfo>>(bm);
                    RadGrid1.VirtualItemCount = count;
                    RadGrid1.DataSource = exam;
                }
            }
        }

        /// <summary>
        /// 绑定期次列表
        /// </summary>
        private void BindQCDDL()
        {
            ddlQC.DataSource = GetQC(RoleId, AppID, false);
            ddlQC.DataValueField = "ID";
            ddlQC.DataTextField = "Title";
            ddlQC.DataBind();
            ddlQC.Items.Insert(0, new ListItem("--请选择--", ""));
        }

        #endregion

        #region 辅助方法

        /// <summary>
        /// 获取期次
        /// </summary>
        /// <param name="roleid">角色ID</param>
        /// <param name="appid">系统ID</param>
        /// <param name="check">是否判断在考试范围内</param>
        /// <returns>期次列表</returns>
        private static List<ModelService.Exam_QC> GetQC(string roleid, string appid, bool check)
        {
            using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
            {
                int count = 0;
                var qc = JsonConvert.DeserializeObject<List<Exam_QC>>(client.GetExamQCList
                       ("QC", roleid, "BmQCList.aspx", appid, 0, 0, out count));
                var list = qc;
                if (check)
                {
                    list = qc.Where(m => m.StartDate <= DateTime.Parse(DateTime.Now.ToShortDateString())
                       && m.EndDate >= DateTime.Parse(DateTime.Now.ToShortDateString())).ToList();
                }
                return list ?? new List<Exam_QC>();
            }
        }

        /// <summary>
        /// 点击【报名缴费】
        /// </summary>
        protected void lbBMPay_Click(object sender, EventArgs e)
        {
            OperationResult result = Do_BM();
            
            if(result.Result || result.Message.Contains("已报名"))
            {
                string orderCode = (result.ReturnValue ?? String.Empty).ToString();
                Do_Pay(orderCode);
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "$.ligerDialog.warn('" + result.Message + "','',RefreshWin);", true);
            }
        }

        /// <summary>
        /// 报名
        /// </summary>
        private OperationResult Do_BM()
        {
            OperationResult result = new OperationResult
            {
                Result = false,
                Message = "操作失败"
            };
            int qcId = int.Parse(hidQCID.Value);

            ////期次信息
            Exam_QC examqc = JsonConvert.DeserializeObject<Exam_QC>(psnClient.GetExamQC(qcId));

            ////获取专家信息
            tb_Emp_Manager empManager = GetEmpManager(UserInfo.CorpUserGuid);

            ////判断是否在【纳入考试人员】范围内
            string expertExamType = psnClient.GetExpertExamType(UserInfo.CorpUserGuid);
            if (String.IsNullOrEmpty(expertExamType) 
                || !examqc.ExamineeType.Contains("," + expertExamType + ","))
            {
                result.Result = false;
                result.Message = "通过省级审核的专家才可以参加考试报名，您不在考试人员范围内，请查看您的审核状态。";
                return result;
            }

            ////报名主表
            ExamBM bmInfo = new ExamBM
            {
                QCId = qcId,
                QCTitle = examqc.Title,
                AreaCode = empManager.DBType,
                CorpName = UserInfo.Name,
                CorpUserGuid = Guid.Parse(UserInfo.CorpUserGuid),
                BMDate = DateTime.Now,
                StartDate = examqc.StartDate,
                EndDate = examqc.EndDate,
                IsDel = false,
                IsrtDate = DateTime.Now
            };
            
            ////报名附表
            ExamBMSub[] bmsubArr = new ExamBMSub[]{
                new ExamBMSub
                {
                    TreeId = qcId,
                    EmpGuid = empManager.EmpGuid,
                    EmpName = empManager.Name,
                    IDCard = empManager.IDCard,
                    IsDel = false,
                    IsrtDate = DateTime.Now
                }
            };
            bmInfo.ExamBMSub = bmsubArr;
            result = JsonConvert.DeserializeObject<ModelService.OperationResult>(psnClient.AddBMInfo(JsonConvert.SerializeObject(bmInfo)));
            return result;
        }

        /// <summary>
        /// 缴费
        /// </summary>
        private void Do_Pay(string orderCode)
        {
            tb_Emp_Manager emp = GetEmpManager(UserInfo.CorpUserGuid);
            tb_ProductInfo ProductInfo = GetExamProductInfo();
            if (emp == null)
            {
                ExecScript("$.ligerDialog.warn('获取用户信息失败。','');");
            }
            else if (ProductInfo == null)
            {
                ExecScript("$.ligerDialog.warn('当前考试还没有确定收费信息，暂时无法缴费。','');");
            }
            else
            {
                PayInfo pi = new PayInfo
                {
                    KeyGUID = Guid.NewGuid(),
                    iTitle = "个人",
                    CorpUserGuid = emp.EmpGuid,
                    LinkPerson = UserInfo.UserName,
                    mobileTel = emp.MobileTel,
                    AreaCode = emp.DBType,
                    bPayStatus = 0,
                    Code = orderCode,
                    GroupCode = GROUP_CODE,
                    FlowCode = "0",
                    OptDate = DateTime.Now,
                    TransDate = DateTime.Now,
                    bCorpKind = int.Parse(RoleId),
                    SumPay = (double)ProductInfo.Fee,
                    IsDel = false,
                    AppID = int.Parse(SystemID)
                };

                PayInfoSub pSub = new PayInfoSub
                {
                    KeyGUID = Guid.NewGuid(),
                    Title = UserInfo.UserName,
                    bKind = PRODUCT_CODE,
                    SourceID = emp.ID,
                    bPayStatus = 0,
                    FlowCode = "0",
                    SumPay = pi.SumPay,
                    IsDel = false
                };
                try
                {
                    pi.PayInfoSub = new PayInfoSub[] { pSub };
                    string rst = psnClient.PayExamFee(JsonConvert.SerializeObject(pi), int.Parse(hidQCID.Value));
                    OperationResult result = JsonConvert.DeserializeObject<OperationResult>(rst);
                    if (!result.Result)
                    {
                        ExecScript("$.ligerDialog.warn('" + result.Message + "','');");
                    }
                    else
                    {
                        RedirectToPay(orderCode);
                    }
                }
                catch (Exception ex)
                {
                    ExecScript("$.ligerDialog.error('" + ex.Message + "','System Error Occorred');");
                }
            }
        }

        /// <summary>
        /// 跳转到支付页
        /// </summary>
        /// <param name="orderCode">订单号</param>
        private void RedirectToPay(string orderCode)
        {
            List<PayRelation> pList = GetPayInfoList();
            PayRelation pr = pList.FirstOrDefault(p => p.Code == orderCode);

            if (pr == null)
            {
                ExecScript("$.ligerDialog.warn('缴费出错，请联系系统管理员。','');");
                return;
            }
            string key = ConfigurationManager.AppSettings["PayWebSitePublicKey"].ToString();
            string iv = ConfigurationManager.AppSettings["PayWebSitePrivateKey"].ToString();
            string OrderId = DESHelper.Encrypt(orderCode, key, iv, Encoding.UTF8);
            string ProductType = DESHelper.Encrypt("EXP", key, iv, Encoding.UTF8);
            string Uid = DESHelper.Encrypt(UserInfo.CorpUserGuid.ToString(), key, iv, Encoding.UTF8);
            object postData = new 
            {
                OrderId = OrderId,
                ProductType = ProductType,
                Uid = Uid
            };
            ExecScript("GoToPayPage('" + JsonConvert.SerializeObject(postData) + "');");
        }

        /// <summary>
        /// 判断指定的期次是否已缴费
        /// </summary>
        /// <param name="qcID">指定的期次ID</param>
        /// <param name="userGuid">指定专家的Guid</param>
        public string GetExamPayStatus(object qcID,object userGuid)
        {
            int _qcID = 0;
            if (int.TryParse(qcID.ToString(), out _qcID) && userGuid!=null)
            {
                string rstStr = psnClient.IsExamFeePaid(_qcID, userGuid.ToString());
                OperationResult result = JsonConvert.DeserializeObject<OperationResult>(rstStr);
                return result.Result ? "已报名缴费" : "未报名缴费";
            }
            else
            {
                return "未报名缴费";
            }
        }

        /// <summary>
        /// 获取当前专家的支付信息列表
        /// </summary>
        /// <returns></returns>
        private List<PayRelation> GetPayInfoList()
        {
            Guid userGuid = Guid.Empty;
            List<PayRelation> payRelList = new List<PayRelation>();
            List<QueryCommonInvoiceCondition> conList = new List<QueryCommonInvoiceCondition> 
            {
                new QueryCommonInvoiceCondition
                {
                    AppID = new ParameterValue<int> { V=int.Parse(SystemID),O = OptEnum.Equal},
                    GroupCode = new ParameterValue<string> { V = GROUP_CODE, O = OptEnum.Equal },
                }
            };

            if (Guid.TryParse(UserInfo.CorpUserGuid, out userGuid))
            {
                string rst = oClient.GetCommonOrders(JsonConvert.SerializeObject(conList), userGuid, 0, 1000);
                payRelList = JsonConvert.DeserializeObject<List<PayRelation>>(rst);
            }
            return payRelList;
        }

        /// <summary>
        /// 获取考试的收费信息
        /// </summary>
        private tb_ProductInfo GetExamProductInfo()
        {
            //绑定企业产品列表
            ProductCondition condition = new ProductCondition() 
            {
                Code = new ParameterValue<string>() { 
                    V = PRODUCT_CODE, 
                    O = OptEnum.Equal
                }, 
                GroupCode = new ParameterValue<string>() {
                    V = GROUP_CODE, 
                    O = OptEnum.Equal 
                }
            };
            List<ProductCondition> query = new List<ProductCondition> { condition };
            string queryStr = JsonConvert.SerializeObject(query);
            string rst = oClient.GetProducts(queryStr, "");
            List<tb_ProductInfo> products = JsonConvert.DeserializeObject<List<tb_ProductInfo>>(rst);
            return products.FirstOrDefault();
        }

        /// <summary>
        /// Exec javascript
        /// </summary>
        /// <param name="script">js content</param>
        private void ExecScript(string script)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "", script, true);
        }

        /// <summary>
        /// 获取当前登录专家信息
        /// </summary>
        /// <param name="empGuid">专家Guid</param>
        private tb_Emp_Manager GetEmpManager(string empGuid)
        {
            Guid empGuid1 = Guid.Empty;
            Guid.TryParse(empGuid, out empGuid1);
            tb_Emp_Manager emp = new tb_Emp_Manager();

            using (PersonServiceClient client = new PersonServiceClient())
            {
                QueryPersonInfoCondition queryCondition = new QueryPersonInfoCondition()
                {
                    EmpGuid = new ParameterValue<Guid> { V = empGuid1, O = OptEnum.Equal }
                };
                List<QueryPersonInfoCondition> query = new List<QueryPersonInfoCondition>() { queryCondition };
                string queryStr = JsonConvert.SerializeObject(query);
                var manages = client.GetEmpManagersAllList(1, 0, queryStr, UserInfo.CurrentArea);
                emp = JsonConvert.DeserializeObject<List<tb_Emp_Manager>>(manages).FirstOrDefault();
            }
            return emp;
        }

        /// <summary>
        /// 组装查询时的tb_Emp_Manager的字符串
        /// </summary>
        /// <returns></returns>
        private string GetQueryEmpCondition()
        {
            tb_Emp_Manager emp = new tb_Emp_Manager
            {
                EmpGuid = Guid.Parse(UserInfo.CorpUserGuid),
                IDCard = txtIDCard.Text.Trim(),
                Name = txtExpertName.Text.Trim()
            };
            return JsonConvert.SerializeObject(emp);
        }

        /// <summary>
        /// 点击【查询】按钮
        /// </summary>
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            RadGrid1.CurrentPageIndex = 0;
            BindData();
            RadGrid1.DataBind();
        }

        /// <summary>
        /// 获取专家手机号(用于未缴费人员)
        /// </summary>
        public string GetEmpPhone(object guid)
        {
            if (guid == null) return "";
            string empGuid = guid.ToString();
            tb_Emp_Manager emp = GetEmpManager(empGuid);
            if (emp == null)
            {
                return "";
            }
            return emp.MobileTel;
        }
        #endregion
    }
}